#include<iostream>
#include<map>
#include<queue>
using namespace std;
int a[10];
map<int,int>b[2];
queue<pair<int,bool> >q;
int change(int x,int op){
    int wz=-1;
    for(int i=9;i>=1;i--){
         a[i]=x%10;
         x/=10;
        
    }
    for(int i=1;i<=9;i++){
        if(a[i]==0){
            wz=i;
            break;
        }
    }
    if(op==1){
        if(wz<=3)return -1;
        swap(a[wz],a[wz-3]);
    }
     if(op==2){
        if(wz>=7)return -1;
         swap(a[wz],a[wz+3]);
    }
    if(op==3){
        if((wz%3)==1)return -1;
        swap(a[wz],a[wz-1]);
    }
      if(op==4){
        if((wz%3)==0)return -1;
        swap(a[wz],a[wz+1]);
    }
    int ans=0;
    for(int i=1;i<=9;i++){
        ans=ans*10+a[i];
    }
    return ans;
}
void check(int x, pair<int,bool> h){
   if(x!=-1){
     if(b[h.second^1].count(x)==true){
        cout<<b[h.second^1][x]+b[h.second][h.first]+1<<endl;
        exit(0);
    }
    else {
        b[h.second][x]=b[h.second][h.first]+1;
        q.push(make_pair(x,h.second));
    }
   }
}
int main(){
    int x;
    cin>>x;
   
    pair<int,bool>fi;
    fi.first=x;
    fi.second=0;
     pair<int,bool>fn;
     fn.first=123804765;
      if(x==fn.first){
        cout<<0;
        return 0;
     }
     fn.second=1;
     q.push(fi);
     q.push(fn);
     while(!q.empty()){
             pair<int,bool>h=q.front();
             q.pop();
             for(int i=1;i<=4;i++){
                int x=change(h.first,i);
                    check(x,h);
             }
     }
    return 0;
}